package com.dykj.fireFighting.server.base.devHisResult.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dykj.fireFighting.api.base.analysis.dto.ComprehensiveQueryDto;
import com.dykj.fireFighting.api.base.analysis.dto.QueryAnalysisDto;
import com.dykj.fireFighting.api.base.analysis.entity.FireAlarmAnalysisResult;
import com.dykj.fireFighting.api.base.analysis.entity.WarningRecovery;
import com.dykj.fireFighting.api.base.analysis.vo.ComprehensiveResultFLVo;
import com.dykj.fireFighting.api.base.dev.entity.vo.FaultVo;
import com.dykj.fireFighting.api.base.devHisResult.entity.DevHisResult;
import com.dykj.fireFighting.api.base.devHisResult.entity.InstructionRecord;
import com.dykj.fireFighting.api.base.devHisResult.entity.TongBiBean;
import com.dykj.fireFighting.api.base.devHisResult.service.IDevHisResultService;
import com.dykj.fireFighting.api.base.devHisResult.vo.ResultVo;
import com.dykj.fireFighting.api.base.enterprise.entity.Enterprise;
import com.dykj.fireFighting.api.base.enterprise.service.IEnterpriseService;
import com.dykj.fireFighting.api.base.system.entity.SysDirectory;
import com.dykj.fireFighting.api.base.system.service.ISysDirectoryService;
import com.dykj.fireFighting.common.core.service.impl.BaseServiceImpl;
import com.dykj.fireFighting.common.core.utils.DateTimeCutUtil;
import com.dykj.fireFighting.common.core.utils.DateUtil;
import com.dykj.fireFighting.common.core.utils.UUIDUtils;
import com.dykj.fireFighting.common.core.vo.PageVo;
import com.dykj.fireFighting.server.base.devHisResult.mapper.DevHisResultMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * 数据统计
 *
 * @Author LIJIANJIE
 * @Date  2021-09-22 10:24:54
 */
@Slf4j
@DubboService
@Transactional(rollbackFor = Exception.class)
public class DevHisResultServiceImpl extends BaseServiceImpl<DevHisResultMapper, DevHisResult> implements IDevHisResultService {

    @Autowired
    private IEnterpriseService enterpriseService;
    @Autowired
    private ISysDirectoryService iSysDirectoryService;



    @Override
    public DevHisResult getUnitNum(String unitId, String beginTime, String endTime) {
        return this.baseMapper.getUnitNum(unitId,beginTime,endTime);
    }

    @Override
    public DevHisResult getCenterNum(List<String> ids, String beginTime, String endTime) {
        return this.baseMapper.getCenterNum(ids,beginTime,endTime);
    }

    @Override
    public DevHisResult getByTime(String date, String unitId) {
        QueryWrapper<DevHisResult> wrapper = new QueryWrapper<>();
        wrapper.eq("unit_id", unitId)
                .eq("result_date", date);
        return this.baseMapper.selectOne(wrapper);
    }

    @Override
    public List<FaultVo> getFaultList(List<String> ids, String beginTime, String endTime) {
        return this.baseMapper.getFaultList(ids,beginTime,endTime);
    }

    @Override
    public int saveOne(Integer type, String unitId, String date) {
        // 查询记录
        DevHisResult devHisResult = this.getByTime(StringUtils.isNotBlank(date) ? date : DateUtil.getDate(),unitId);
        // 如果不存在，新增
        if (devHisResult == null) {
            devHisResult = new DevHisResult();
            // 获取监控中心
            Enterprise enterprise = enterpriseService.queryById(unitId);
            // 如果存在bingdingCode，查监控中心
            if (enterprise != null && enterprise.getBindingCode() != null) {
                Enterprise center = enterpriseService.getInfoByBindingCode(enterprise.getBindingCode());
                if (center != null) {
                    devHisResult.setCenterUnitId(center.getId() + "");
                }
            }
            devHisResult.setId(UUIDUtils.get32UUID());
            devHisResult.setUnitId(unitId);
            devHisResult.setFireAlarm(0);
            devHisResult.setFault(0);
            devHisResult.setReview(0);
            devHisResult.setReviewAll(0);
            devHisResult.setManagement(0);
            devHisResult.setManagementAll(0);
            devHisResult.setEarlyWarning(0);
            try {
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                devHisResult.setResultDate(formatter.parse(DateUtil.getDate()));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            this.baseMapper.insert(devHisResult);
            System.out.println("插入了一条数据:" + devHisResult.getUnitId());

        }
        // 存在，直接修改 1 火警 2 故障 3 预警 4 有效复核 5 复核总数 6 有效处置 7 处置总数
        if (type == 1) {
            devHisResult.setFireAlarm(devHisResult.getFireAlarm() + 1);
        } else if (type == 2) {
            devHisResult.setFault(devHisResult.getFault() + 1);
        } else if (type == 3) {
            devHisResult.setEarlyWarning(devHisResult.getEarlyWarning() + 1);
        } else if (type == 4) {
            devHisResult.setReview(devHisResult.getReview() + 1);
        } else if (type == 5) {
            devHisResult.setReviewAll(devHisResult.getReviewAll() + 1);
        } else if (type == 6) {
            devHisResult.setManagement(devHisResult.getManagement() + 1);
        } else if (type == 7) {
            devHisResult.setManagementAll(devHisResult.getManagementAll() + 1);
        }
        return this.baseMapper.updateById(devHisResult);
    }

    @Override
    public List<DevHisResult> getByUnitId(String unitId, String centerUnitId) {
        QueryWrapper<DevHisResult> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(unitId),"unit_id", unitId)
                .eq(StringUtils.isNotBlank(centerUnitId),"center_unit_id", centerUnitId)
                .eq("result_date", DateUtil.getDate());
        return this.baseMapper.selectList(wrapper);
    }

    @Override
    public int updateByUnitId(InstructionRecord instructionRecord) {
        return this.baseMapper.updateByUnitId(instructionRecord);
    }


    @Override
    public List<TongBiBean> getTongBiByMonth(String type, String newTime, String oldTime, Long enterpriseId,String socialUnitId) {
         if (type.equals("1")){
            return this.baseMapper.getTongBiBeanList(newTime,oldTime,enterpriseId,socialUnitId);
        }
        return this.baseMapper.getHuanBiBeanList(newTime,oldTime,enterpriseId,socialUnitId);
    }

    @Override
    public PageVo<WarningRecovery> getList(QueryAnalysisDto queryAnalysis) {
        Page page = new Page();
        // 设置当前页码
        page.setCurrent(queryAnalysis.getPage());
        // 设置页大小
        page.setSize(queryAnalysis.getLimit());
        return new PageVo<WarningRecovery>(this.baseMapper.getList(page, queryAnalysis));
    }

    @Override
    public List<WarningRecovery> getChartDate(QueryAnalysisDto queryAnalysis) {
        return this.baseMapper.getChartDate(queryAnalysis);
    }

    @Override
    public FireAlarmAnalysisResult getFireNum(QueryAnalysisDto queryAnalysis) {
        return this.baseMapper.getFireNum(queryAnalysis);
    }

    @Override
    public List<FireAlarmAnalysisResult> getFireChartData(QueryAnalysisDto queryAnalysis) {
        return this.baseMapper.getFireChartData(queryAnalysis);
    }

    @Override
    public List<FireAlarmAnalysisResult> getFaultChartData(QueryAnalysisDto queryAnalysis) {
        return this.baseMapper.getFaultChartData(queryAnalysis);
    }

    @Override
    public PageVo<FireAlarmAnalysisResult> getFaultDangerList(QueryAnalysisDto queryAnalysis) {
        Page page = new Page();
        // 设置当前页码
        page.setCurrent(queryAnalysis.getPage());
        // 设置页大小
        page.setSize(queryAnalysis.getLimit());
        return new PageVo<FireAlarmAnalysisResult>(this.baseMapper.getFaultDangerList(page, queryAnalysis));
    }

    @Override
    public List<FireAlarmAnalysisResult> getFaultRankingList(QueryAnalysisDto queryAnalysis) {
        return this.baseMapper.getFaultRankingList(queryAnalysis);
    }

    @Override
    public List<ResultVo> getUnitDate(String centerId, String unitId, String beginTime, String endTime) {
        return this.baseMapper.getunitDate(centerId,unitId,beginTime,endTime);
    }

    @Override
    public List<ResultVo> getMonthDate(String unitId, String beginTime, String endTime) {
        return this.baseMapper.getmonthDate(unitId,beginTime,endTime);
    }

    @Override
    public List<ResultVo> getQuarterDate(String unitId, String beginTime, String endTime) {
        return this.baseMapper.getQuarterDate(unitId,beginTime,endTime);
    }

    @Override
    public List<ResultVo> getYearDate(String unitId, String beginTime, String endTime) {
        return this.baseMapper.getYearDate(unitId,beginTime,endTime);
    }

    @Override
    public List<ComprehensiveResultFLVo> getFuHeLvQSByUnits(ComprehensiveQueryDto queryDto) {
        return this.baseMapper.getFuHeLvQSByUnits(queryDto);
    }

    @Override
    public List<ComprehensiveResultFLVo> getFuHeLvQSByArea(ComprehensiveQueryDto queryDto) {
        return this.baseMapper.getFuHeLvQSByArea(queryDto);
    }

    @Override
    public List<ComprehensiveResultFLVo> getFuHeLvQSByIndustry(ComprehensiveQueryDto queryDto) {
        return this.baseMapper.getFuHeLvQSByIndustry(queryDto);
    }

    @Override
    public List<ComprehensiveResultFLVo> getFuHeLvPHByUnits(ComprehensiveQueryDto queryDto) {
        return this.baseMapper.getFuHeLvPHByUnits(queryDto);
    }

    @Override
    public List<ComprehensiveResultFLVo> getFuHeLvPHByArea(ComprehensiveQueryDto queryDto) {
        return this.baseMapper.getFuHeLvPHByArea(queryDto);
    }

    @Override
    public List<ComprehensiveResultFLVo> getFuHeLvPHByIndustry(ComprehensiveQueryDto queryDto) {
        return this.baseMapper.getFuHeLvPHByIndustry(queryDto);
    }

    @Override
    public List<ComprehensiveResultFLVo> getChuZhiLvQSByUnits(ComprehensiveQueryDto queryDto) {
        return this.baseMapper.getChuZhiLvQSByUnits(queryDto);
    }

    @Override
    public List<ComprehensiveResultFLVo> getChuZhiLvQSByArea(ComprehensiveQueryDto queryDto) {
        return this.baseMapper.getChuZhiLvQSByArea(queryDto);
    }

    @Override
    public List<ComprehensiveResultFLVo> getChuZhiLvQSByIndustry(ComprehensiveQueryDto queryDto) {
        return this.baseMapper.getChuZhiLvQSByIndustry(queryDto);
    }

    @Override
    public List<ComprehensiveResultFLVo> getChuZhiLvPHByUnits(ComprehensiveQueryDto queryDto) {
        return this.baseMapper.getChuZhiLvPHByUnits(queryDto);
    }

    @Override
    public List<ComprehensiveResultFLVo> getChuZhiLvPHByArea(ComprehensiveQueryDto queryDto) {
        return this.baseMapper.getChuZhiLvPHByArea(queryDto);
    }

    @Override
    public List<ComprehensiveResultFLVo> getChuZhiLvPHByIndustry(ComprehensiveQueryDto queryDto) {
        return this.baseMapper.getChuZhiLvPHByIndustry(queryDto);
    }

    /**
     *
     * @param queryDto
     * @param resDateNameList  sql查询后返回的list将resdate resname 组成的集合
     * @return
     * @throws ParseException
     * 时间粒度 timeGranularity   1:年，2：季 ，3：月，4：日
     */
    @Override
    public List<ComprehensiveResultFLVo> buling(ComprehensiveQueryDto queryDto, List<String> resDateNameList) throws ParseException {
        List<ComprehensiveResultFLVo> list=new ArrayList<ComprehensiveResultFLVo>();
        List<String> newList = new ArrayList<>();

        switch (queryDto.getTimeGranularity()){
            case "1":
                List<String> yearList = DateTimeCutUtil.cutByType(queryDto.getBeginTime(), queryDto.getEndTime(), "year");
                newList = getNewList(queryDto.getDataDimension(), queryDto.getUnitIdList(), yearList);
                break;
            case "2":
                List<String> quarterList = DateTimeCutUtil.cutByType(queryDto.getBeginTime(), queryDto.getEndTime(), "quarter");
                newList = getNewList(queryDto.getDataDimension(), queryDto.getUnitIdList(), quarterList);
                break;
            case "3":
                List<String> monthList = DateTimeCutUtil.cutByType(queryDto.getBeginTime(), queryDto.getEndTime(), "month");
                newList = getNewList(queryDto.getDataDimension(), queryDto.getUnitIdList(), monthList);
                break;
            case "4":
                List<String> dayList = DateTimeCutUtil.cutByType(queryDto.getBeginTime(), queryDto.getEndTime(), "day");
                newList = getNewList(queryDto.getDataDimension(), queryDto.getUnitIdList(), dayList);
                break;
        }
        List<String> chayi = DateTimeCutUtil.subList2(newList, resDateNameList);
        for (String s:chayi
        ) {
            String[] split = s.split(",");
            ComprehensiveResultFLVo comprehensiveResultFLVo = new ComprehensiveResultFLVo();
            comprehensiveResultFLVo.setResDate(split[0]);
            comprehensiveResultFLVo.setResName(split[1]);
            comprehensiveResultFLVo.setResValue("0");
            list.add(comprehensiveResultFLVo);
        }
        return list;
    }

    /**
     *
     * @param dataDimension 综合查询数据维度 1单位 2区域 3行业
     * @param unitIdList  单位id集合
     * @param dateList  年 或者月或者日或者季度  的集合
     * @return
     */
    public  List<String> getNewList(String dataDimension,List<String> unitIdList,List<String> dateList ){
        List<SysDirectory> industry = iSysDirectoryService.queryDataByType("industry");
        List<SysDirectory> quyeList = iSysDirectoryService.getByParentCode("130200000000");

        // 数据维度 1单位 2区域 3行业
        List<String> newList = new ArrayList<>();
        for (int i = 0; i <dateList.size() ; i++) {
            switch (dataDimension){
                case "1":
                 List<Enterprise> enterpriseList=enterpriseService.queryByIds(unitIdList);
                    for (int j = 0; j <enterpriseList.size() ; j++) {
                        newList.add(dateList.get(i) +","+ enterpriseList.get(j).getEnterpriseName());
                    }
                    break;
                case "2":
                    for (int j = 0; j <quyeList.size() ; j++) {
                        newList.add(dateList.get(i) +","+ quyeList.get(j).getValue());
                    }
                    break;
                case "3":
                    for (int j = 0; j <industry.size() ; j++) {
                        newList.add(dateList.get(i) +","+ industry.get(j).getValue());
                    }
                    break;
            }
        }
        return newList;
    }


    public String getPercent(int x,int total){
        String result="";
        double x_double=(x-total)*1.0*100;
        double tempresult=x_double/total;
        DecimalFormat df1 = new DecimalFormat("#.00");
        result= df1.format(tempresult);
        return result;
    }
}
